package org.example.judge_contest.controller;


import lombok.extern.slf4j.Slf4j;
import org.example.judge_common.annotation.AuthAnnotation;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestContestParams;
import org.example.judge_common.entity.ResponseResult;
import org.example.judge_common.util.MyUtils;
import org.example.judge_contest.service.ContestProblemService;
import org.example.judge_contest.service.ContestRecordService;
import org.example.judge_contest.service.ContestRegisterService;
import org.example.judge_contest.service.ContestService;
import org.example.judge_pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/contest")
@Slf4j
public class ContestController {

    @Qualifier("ContestServiceImpl")
    @Autowired
    private ContestService contestService;

    @Qualifier("ContestProblemServiceImpl")
    @Autowired
    private ContestProblemService contestProblemService;

    @Qualifier("ContestRegisterServiceImpl")
    @Autowired
    private ContestRegisterService contestRegisterService;
    @Qualifier("ContestRecordServiceImpl")
    @Autowired
    private ContestRecordService contestRecordService;

    @PostMapping("/search")
    @AuthAnnotation(exist = false)
    public ResponseResult list(RequestContestParams params, HttpServletRequest request){
        if (params==null) {
            params = new RequestContestParams();
        }
        User loginUser = (User) request.getAttribute("loginUser");
        if(!Auth.isAdmin(loginUser)){ //无管理员权限
            params.setIshow(0);  //只展示可见的
//            params.setAuth(0);  //公开比赛
        }
        PageResult<Contest> res = contestService.search(params);
        return ResponseResult.success().setData(res);
    }
    @PostMapping("/detail/{id}")
    @AuthAnnotation(Auth.CLIENT)
    public ResponseResult selectById(@PathVariable String id, HttpServletRequest request,String resp){
        Contest byId = contestService.getById(id);
        if(byId==null)return ResponseResult.NotData();
        if("title".equals(resp)){ //只获取title
            return ResponseResult.success().setData(byId.getTitle());
        }
        if("status".equals(resp)){
            return ResponseResult.success().setData(byId.getStatus());
        }
//        System.out.println(resp);
        User loginUser = (User) request.getAttribute("loginUser");

        if(!Auth.isAdmin(loginUser)&&byId.getStatus()==0){
            byId.setProblems(null);  //去除题目列表
        }else if(byId.getStatus()==1){
            //判断用户是否报名
            ContestRegister one = contestRegisterService.getByUserIdAndContestId(loginUser.getId(),id);
            if(one!=null&&one.getStatus()==0){ //已报名且可用
                //添加题目列表
                List<ContestProblem> list = contestProblemService.listByContestId(id);
                byId.setProblems(list);
            }
        }else if(byId.getStatus()==2){  //比赛已结束，题目开放
            //添加题目列表
            List<ContestProblem> list = contestProblemService.listByContestId(id);
            byId.setProblems(list);
        }
        if(byId.getStatus()!=0){ //比赛已开始，获取通过率
            for (ContestProblem contestProblem : byId.getProblems()) {
                //提交/通过数量
                int acceptSum = contestRecordService.countContestSubmit(contestProblem.getContestId(), contestProblem.getProblemId(), 0);
                int submitSum = contestRecordService.countContestSubmit(contestProblem.getContestId(), contestProblem.getProblemId(), null);
                contestProblem.setAcceptSum(acceptSum);
                contestProblem.setSubmitSum(submitSum);
                //该题目已通过
                if (contestRecordService.isAc(contestProblem.getContestId(),contestProblem.getProblemId(),loginUser.getId(),0)) {
                    contestProblem.setStatus(0);
                }else if(contestRecordService.isAc(contestProblem.getContestId(),contestProblem.getProblemId(),loginUser.getId(),null)){
                    contestProblem.setStatus(1);//改题目已提交
                }else contestProblem.setStatus(-1);

            }
        }

        if(!Auth.isAdmin(loginUser)) byId.setPassword(null);  //删除邀请码

        return ResponseResult.success().setData(byId);
    }

    @PostMapping("/save")
    @AuthAnnotation({Auth.ADMINISTRATOR})
    public ResponseResult save(@RequestBody Contest contest,HttpServletRequest request){
        if(contest.getAuth()==1&& MyUtils.isEmpty(contest.getPassword())){
            return ResponseResult.fail("私密比赛密码不能为空");
        }
        if(contest.getEndTime().getTime()-contest.getStartTime().getTime()<=1000*60*1){
            return ResponseResult.fail("比赛时间过短");
        }
        if(contest.getStartTime().getTime()-System.currentTimeMillis()<=1000*60*5){
            return ResponseResult.fail("比赛开始时间最少设置五分钟以后");
        }
        if(contest.getSealRank()==0&&contest.getSealRankTime().getTime()<contest.getStartTime().getTime()){
            return ResponseResult.fail("封榜时间必须设置在比赛开始以后");
        }
        if(contest.getRegisterEndTime().getTime()>contest.getEndTime().getTime()){
            return ResponseResult.fail("报名结束时间必须设置在比赛结束之前");
        }

        User loginUser = (User) request.getAttribute("loginUser");
        contest.setAuthorId(loginUser.getId());
        contestService.save(contest);
        return ResponseResult.success();
    }
    @PutMapping("update")
    @AuthAnnotation({Auth.ADMINISTRATOR})
    public ResponseResult update(@RequestBody Contest contest,HttpServletRequest request){
        if(MyUtils.isEmpty(contest.getId())){

            User loginUser = (User) request.getAttribute("loginUser");
            log.warn("用户Id：{}:{}试图修改没有ID的比赛信息",loginUser.getId(),loginUser.getUsername());
            return ResponseResult.fail("比赛ID不能为空");
        }
        contestService.updateById(contest);
        return ResponseResult.success();
    }
    @DeleteMapping("/delete/{id}")
    @AuthAnnotation({Auth.ADMINISTRATOR})
    public ResponseResult deleteById(@PathVariable("id") String contestId,HttpServletRequest request){
        User loginUser = (User) request.getAttribute("loginUser");
        log.info("用户id{}：{}执行了删除比赛{}操作",loginUser.getId(),loginUser.getUsername(),contestId);
        contestService.removeById(contestId);
        return ResponseResult.success();
    }

}
